﻿using System;
using System.Collections.Generic;
using System.Text;
using net.xBei.Helper;
using xBei.Redis.Extension;

namespace net.xBei.Repository
{
    public class CacheRepository
    {
        private readonly RedisClient redisClient;

        public CacheRepository(RedisClient redisClient) {
            this.redisClient = redisClient;
        }

        public CacheRepository Set<T>(string key, T data, int seconds, CacheDependent dependent) where T : class, new() {
            redisClient.Enqueue($"dependent:{dependent.GetKey()}", key);
            redisClient.SetValue(key, data, seconds);
            return this;
        }
        public CacheRepository Remove(CacheDependent dependent) {
            var key = dependent.GetKey();
            var list = redisClient.GetList(key, 1, int.MaxValue);
            list.Items.ForEach(k => {
                redisClient.Remove(k);
            });
            redisClient.Remove(key);
            return this;
        }
        public class CacheDependent
        {
            private readonly string key;

            public CacheDependent(string key) {
                this.key = key;
            }
            public string GetKey() {
                return key;
            }
        }
    }
}
